package org.teachertools.services;

import java.util.List;

import javax.persistence.Query;

import org.hibernate.HibernateException;
import org.springframework.stereotype.Repository;
import org.teachertools.common.ValidationUtils;
import org.teachertools.data.Matiere;
import org.teachertools.services.exception.ServiceException;

@Repository
public class MatiereService extends GenericService<Matiere> {

    @SuppressWarnings("unchecked")
    public List<Matiere> getMatiereForCategorieId(Long idCategorie) throws ServiceException {
        try {
            String request = "from Matiere where categorie.id = :label_1 order by nom";
            Query query = this.entityManager.createQuery(request);
            query.setParameter("label_1", idCategorie.longValue());
            List<Matiere> matieres = query.getResultList();
            // ((Session) this.entityManager.getDelegate()).evict(matieres);
            return matieres;
        } catch (HibernateException e) {
            this.logger.error(e.getCause(), e);
            throw new ServiceException(e, "error.db.param", new String[] { e.getCause().getMessage() });
        }
    }

    @Override
    protected Class<Matiere> getObjectClass() {
        return Matiere.class;
    }

    @Override
    protected Query getSearchQuery(Matiere matiere) {
        StringBuffer request = new StringBuffer();
        request.append("from Matiere entity");

        // if (initializeSecondLevelObjects)
        // request.append(" left join fetch entity.categorie");

        request.append(" where 1 = 1");

        if (ValidationUtils.isNotEmpty(matiere.getNom())) {
            request.append(" and upper(entity.nom) like upper(:label_0)");
        }
        if (ValidationUtils.isNotEmpty(matiere.getCategorie())
                && ValidationUtils.isNotEmpty(matiere.getCategorie().getId())) {
            request.append(" and entity.categorie.id = :label_1");
        }

        Query query = this.entityManager.createQuery(request.toString());

        if (ValidationUtils.isNotEmpty(matiere.getNom())) {
            query.setParameter("label_0", prepareQueryParam(matiere.getNom()));
        }
        if (ValidationUtils.isNotEmpty(matiere.getCategorie())
                && ValidationUtils.isNotEmpty(matiere.getCategorie().getId())) {
            query.setParameter("label_1", matiere.getCategorie().getId());
        }
        return query;
    }

}
